package com.woniuxy.main.login_yjj.handler;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.woniuxy.main.login_yjj.pojo.Mine;
import com.woniuxy.main.login_yjj.pojo.LoginUser;
import com.woniuxy.main.login_yjj.pojo.User_Yjj;
import com.woniuxy.main.login_yjj.pojo.venue;
import com.woniuxy.main.login_yjj.service.LoginService;
import com.woniuxy.main.mycenter_ty.pojo.User_Ty;
import com.woniuxy.main.mycenter_ty.service.MyCenterService;
import com.woniuxy.main.utils.MessageUtil;
import com.woniuxy.main.utils.RegexUtil;
import lombok.Data;
import com.woniuxy.main.login_yjj.pojo.Mine;

@Controller
@Data
public class LoginHandler {
	private static String myphone;
	private static String mypwd;
	private LinkedHashMap<String, Mine> map=new LinkedHashMap<String, Mine>();
	private String isout;
	private String what;
	private String who;
	private String alert;
	private Subject sub;
	private Session session;
	List<venue> ven=new ArrayList<venue>();
	List<User_Yjj> coch=new ArrayList<User_Yjj>();
	@Autowired
	private LoginService service;
	@Autowired
	private MyCenterService personCenterservice;

	
	/**
	 * 请求登录页面
	 * @return
	 */
	@RequestMapping("/start")
	public String start() {
		return "/login.html";
	}

	
	/**
	 * 短信验证码请求
	 * @param phone
	 * @param mo
	 * @return
	 */
	@RequestMapping("/code")
	@ResponseBody
	public String code(String phone,Model mo) {
		System.out.println(phone);
		String data=null;
		if(phone.matches(RegexUtil.REGEX_MOBILE)) {
			//连接数据库查询用户是否存在,有这个用户就返回一个提示，没有就直接调用验证码的方法
			//发送验证码次数不多，谨慎使用
			LoginUser lu=new LoginUser();
			lu=service.finduser(new LoginUser(phone,null,0,0));
			if(lu!=null) {
				System.out.println("手机号已存在");
				data="手机号已存在";
			}else {
				System.out.println("未注册手机号");
				// 发送短信至手机号
				MessageUtil messageUtil = new MessageUtil();
				messageUtil.sendMessage(phone);
			}
		}
		return data;
	}
	
	
	
	@RequestMapping("/loadregister")
	public String loadregister() {
		return "register.html";
	}
	
	
	@RequestMapping("/loadlogin")
	public String loadlogin() {
		return "login.html";
	}
	
	
	/**
	 * 注册
	 * @param phone
	 * @param code
	 * @param pwd
	 * @param mo
	 * @return
	 */
	@RequestMapping("/register")
	public String register(String phone,String code,String pwd,Model mo) {
		String data=null;
		System.out.println(phone+code+pwd);
		//判断验证码，正确就去数据库插入，跳到登入页面，失败则返回到注册页面给与提示
		if(code.equals(MessageUtil.mycode)) {
			System.out.println(MessageUtil.mycode);
			//插入数据库操作。。。。。。。。。。。。。。。。
			Md5Hash md=new Md5Hash(pwd, phone, 998);
			service.adduser(new LoginUser(phone,md.toString(),0,0));
			data="/code.html";
		}else {
			System.out.println(MessageUtil.mycode);
			data="/ecode.html";
		}
		return data;
	}
	
	
	/**
	 *  登录
	 * @param phone
	 * @param pwd
	 * @param mo
	 * @return
	 */
	@RequestMapping("/login")
	public String login(String phone,String pwd,Model mo) {
		String yn="";
		//连接数据库进行登入判断
		//盐值加密
		Md5Hash md=new Md5Hash(pwd, phone, 998);
		UsernamePasswordToken token=new UsernamePasswordToken(phone,md.toString());
		sub=SecurityUtils.getSubject();
		session=sub.getSession(); 
		User_Yjj currentUser=null;
//		LoginUser user=service.login(new LoginUser(phone,pwd));
		try {
			//去认证
			sub.login(token);
			 //去数据库查找这个手机号的用户
			currentUser =service.findUserByPhone(phone);
			session.setAttribute("currentUser", currentUser);
			//返回一个页面用于判断
			yn="/code.html";
		} catch (Exception e) {
			System.out.println("登入失败！");
			yn="/ecode.html";
		}
		if(currentUser!=null) {
			if(map.get(currentUser.getUser_phone())==null) {
				myphone=currentUser.getUser_phone();
				mypwd=currentUser.getUser_pwd();
				map.put(myphone, new Mine(myphone,mypwd));
				isout="ok";
			}else {
				isout="warn";
				map.remove(currentUser.getUser_phone());
				if(isout=="ok") {
					sub.logout();
				}
			}	
		}
		return yn;
	}
	
	
	/**
	 * 请求忘记密码页面
	 * @return
	 */
	@RequestMapping("/forget")
	public String forget() {
		return "forget.html";
	}
	
	
	
	@RequestMapping("/ressend")
	@ResponseBody
	public String ressend(String phone,Model mo) {
		System.out.println(phone);
		String data=null;
		if(phone.matches(RegexUtil.REGEX_MOBILE)) {
			//连接数据库查询用户是否存在,有这个用户就返回一个提示，没有就直接调用验证码的方法
			//发送验证码次数不多，谨慎使用
			LoginUser lu=new LoginUser();
			lu=service.finduser(new LoginUser(phone,null,0,0));
			if(lu!=null) {
				System.out.println("是我们的用户");
				data="null";
				//发送短信至手机号
				MessageUtil messageUtil = new MessageUtil();
				messageUtil.sendMessage(phone);
			}else {
				data="手机号输入错误";
			}
			}
		return data;
	}
	
	
	/**
	 * 修改密码请求
	 * @param phone
	 * @param code
	 * @param pwd
	 * @return
	 */
	@RequestMapping("/updatp")
	@ResponseBody
	public String updatp(String phone,String code,String pwd) {
		String data="";
//		MessageUtil.mycode
		if(code.equals(MessageUtil.mycode)) {
			//连接数据库进行密码修改
			Md5Hash md=new Md5Hash(pwd, phone, 998);
			service.updatp(new LoginUser(phone,md.toString(),0,0));
			data="ok";
		}else {
			data="验证码有误";
		}
		return data;	
	}

	
	/**
	 * 无权访问页面
	 * @return
	 */
	@RequestMapping("/no")
	public String no() {
		org.apache.shiro.subject.Subject sub=SecurityUtils.getSubject();
		return "/no.html";
	}
	
	
	/**
	 * 请求主页面
	 * @return
	 */
	@RequestMapping("/main")
	public ModelAndView main() {
		//将登入的所有人分配到对应角色展现的页面
				org.apache.shiro.subject.Subject sub=SecurityUtils.getSubject();
				ModelAndView mo=new ModelAndView();
				User_Yjj us=null;
				String isok=null;
				String isem=null;
				System.out.println("当前在线人数："+map.size());
				//各个角色登入后的主页面附带自己个人的基本信息
				mo.addObject("everyone",sub.getSession().getAttribute("currentUser"));
				String account = (String) SecurityUtils.getSubject().getPrincipal();
				User_Ty user_yj = personCenterservice.queryAllInfoByPhone(account); // 个人资料
				if(sub.isPermitted("user")) {
					//普通学员返回的页面
					if(myphone!=null) {
						us=service.findUserByPhone(myphone);
						System.out.println(us);
						if(us.getUser_headimg().length()>1&&us.getUser_name().length()>1&&us.getUser_nickname().length()>1) {
							isem="ok";
						}else {
							isem="null";
						}
						if(us.getUser_pwd().equals(mypwd)) {
							isok="ok";
						}else {
							isok="warn";
						}
					}
					mo.setViewName("/main.html");
					mo.addObject("isout", isout);
					mo.addObject("isem", isem);
//					mo.addObject("ok", isok);
					mo.addObject("user", "./img/头像 (2).png");
					mo.addObject("who", "user");
					mo.addObject("alive", "/chat/add.html");
					mo.addObject("load", "/chat/personcenter");
					mo.addObject("loadfriend", "/chat/index2");
					mo.addObject("main", "/chat/main");
					mo.addObject("userid", user_yj.getUser_id()+"");
					System.out.println("我是学员");
					return mo;
				}
				if(sub.isPermitted("coach")) {
					//教练页面
					if(myphone!=null) {
						us=service.findUserByPhone(myphone);
						System.out.println(us);
						if(us.getUser_headimg().length()>1&&us.getUser_name().length()>1&&us.getUser_nickname().length()>1) {
							isem="ok";
						}else {
							isem="null";
						}
						if(us.getUser_pwd().equals(mypwd)) {
							isok="ok";
						}else {
							isok="warn";
						}
					}
					mo.addObject("isout", isout);
					mo.setViewName("/main.html");
					mo.addObject("isem", isem);
//					mo.addObject("ok", isok);
					mo.addObject("who", "coach");
					mo.addObject("alive", "/chat/add.html");
					mo.addObject("load", "/chat/personcenter");
					mo.addObject("loadfriend", "/chat/index2");
					mo.addObject("main", "/chat/main");
					mo.addObject("user", "./img/头像 (1).png");
					mo.addObject("userid", user_yj.getUser_id()+""); 
					System.out.println("我是教练");
					return mo;
				}
//				if(sub.isPermitted("venue")) {
//					//场馆页面
//					mo.setViewName("/main.html");
//					mo.addObject("user", "./img/头像 (2).png");
//					mo.addObject("who", "venue");
//					mo.addObject("alive", "/chat/null");
//					mo.addObject("load", "hello");
//					mo.addObject("loadfriend", "/chat/null");
//					System.out.println("场馆登入");
//					return mo;
//				}
//				if(sub.isPermitted("supper")) {
//					//管理页面
//					mo.setViewName("/main.html");
//					mo.addObject("user", "./img/头像 (3).png");
//					mo.addObject("who", "supper");
//					mo.addObject("alive", "/chat/null");
//					mo.addObject("load", "hello");
//					mo.addObject("loadfriend", "/chat/null");
//					System.out.println("超管驾到");
//					return mo;
//				}
				mo.setViewName("/main.html");
				mo.addObject("user", "./img/头像.png");
				mo.addObject("who", "tourists");
				mo.addObject("loadfriend", "#");
				mo.addObject("alive", "#");
				mo.addObject("load", "#");
				mo.addObject("main", "#");
				System.out.println("游客路过");
				return mo;
	}
	
	
	/**
	 * 注销
	 * @return
	 */
	@RequestMapping("/out")
	public String out(){
		sub=SecurityUtils.getSubject();
		if(sub.getPrincipal()!=null) {
			map.remove(sub.getPrincipal().toString());
		}
		
		sub.logout();
	//重定向到商品查询页面
	return "redirect:/start";
	}
	//用户协议
		@RequestMapping("/advice")
		public String advice() {
			return "/advice.html";
		}
		@RequestMapping("/search")
		public String search(String text,String user_name) {
			alert=null;
			who=null;
			what=null;
			who=text;
			alert=user_name;
			ven.clear();
			coch.clear();
			if(text.equals("教练")) {
				//连接数据库查找教练表
				coch=service.findcoch();
				List<User_Yjj> coach=new ArrayList<User_Yjj>();
				if(coch.size()!=0) {
					for (User_Yjj v : coch) {
						if(v.getUser_name().contains(user_name)) {
							coach.add(v);
						}
					}
					if(coach.size()!=0) {
						coch=coach;
						what="为您找到与";
					}
                    if(coach.size()==0) {
						what="没有找到与";
					}
				}
			}
            if(text.equals("场馆")) {
				//同上
            	List<venue> venue=new ArrayList<venue>();
				ven=service.findvenue();
				if(ven.size()!=0) {
					for (venue v : ven) {
						if(v.getVenue_name().contains(user_name)) {
							venue.add(v);
						}
					}
					System.out.println("<<<<<<<<<<<<<<");
					if(venue.size()!=0) {
						 ven=venue;
						what="为您找到与";
					}
                    if(venue.size()==0){
						what="没有找到与";
					}
				}
			}
            if(text.equals("学员")) {
            	//同上
            	List<User_Yjj> user=new ArrayList<User_Yjj>();
				coch=service.findus();
				if(coch.size()!=0) {
					for (User_Yjj v : coch) {
						if(v.getUser_name().contains(user_name)) {
							user.add(v);
						}
					}
					if(user.size()!=0) {
						coch=user;
						what="为您找到与";
					}
					if(user.size()==0) {
						what="没有找到与";
					}
				}
			}
			return "redirect:/show";
		}
		@RequestMapping("/show")
		public ModelAndView show() {
			ModelAndView mo=new ModelAndView();
			if(coch.size()!=0) {
				mo.addObject("coach",coch);
				mo.addObject("who", who);
				mo.addObject("what", what);
				mo.addObject("alert", alert);
				if(who.equals("教练")) {
					mo.addObject("lujin","/chat/showcoach.html");
				}
				else if(who.equals("学员")) {
					mo.addObject("lujin", "/chat/showstudent.html");
				}else {
					mo.addObject("lujin", "#");
				}
			}
			if(ven.size()!=0) {
				System.out.println(ven);
				mo.addObject("venue",ven);
				mo.addObject("who", who);
				mo.addObject("what", what);
				mo.addObject("alert", alert);
				mo.addObject("ven", "/chat/showvenue.html");
			}
			System.out.println(who+":"+what+":"+alert);
			mo.setViewName("/show");
			return mo;
		}
}
